import { useState, useEffect } from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from 'recharts';
import { MetricsData } from '@/types/data';
import useInterval from '@/hooks/useInterval';

export default function MetricsCard({ data }: { data: MetricsData }) {
  const [displayData, setDisplayData] = useState<{
    increaseRateNum: number;
    prediction: number;
    capacity: number;
  }>({
    increaseRateNum: 0,
    prediction: data.prediction,
    capacity: data.capacity
  });

 
  const calculateIncreaseRate = () => {
    const dataPoints = data.trendData.length;
    const recentData = data.trendData.slice(Math.max(0, dataPoints - 50));
    const previousData = data.trendData.slice(Math.max(0, dataPoints - 100), Math.max(0, dataPoints - 50));
    
    const recentSum = recentData.reduce((sum, item) => sum + item.y1, 0);
    const previousSum = previousData.reduce((sum, item) => sum + item.y1, 0);
    

    const increaseRate = previousSum > 0 
      ? ((recentSum - previousSum) / previousSum * 100).toFixed(1)
      : "0.0";

    return parseFloat(increaseRate);
  };


  useEffect(() => {
    setDisplayData({
      increaseRateNum: calculateIncreaseRate(),
      prediction: data.prediction,
      capacity: data.capacity
    });
  }, [data]);


  useInterval(() => {
    setDisplayData(prev => {
      const randomFactor = () => 1 + (Math.random() * 0.02 - 0.01); 
      
      return {
        increaseRateNum: calculateIncreaseRate() * randomFactor(),
        prediction: data.prediction * randomFactor(),
        capacity: data.capacity * randomFactor()
      };
    });
  }, 2000);
  const increaseData = [
    { name: '用电增长', value: Math.max(0, displayData.increaseRateNum) },
    { name: '用电减少', value: Math.abs(Math.min(0, displayData.increaseRateNum)) }
  ];

  const loadData = [
    { name: '预测负荷', value: displayData.prediction },
    { name: '剩余容量', value: displayData.capacity - displayData.prediction }
  ];

  const COLORS = ['#00E5FF', '#FF0080', '#00FFA3', '#FFC700'];

  return (
    <div className="flex flex-col h-full">
      <h2 className="text-xl font-medium mb-4 font-['Google_Sans']">当日用电分析</h2>
      <div className="min-h-[400px] grid grid-cols-2 gap-4">
        <div className="flex flex-col">
          <h3 className="text-center mb-2 text-gray-300">用电增幅</h3>
          <div className="flex-1">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={increaseData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  paddingAngle={5}
                  dataKey="value"
                >
                  {increaseData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: '#333',
                    borderColor: '#555',
                    borderRadius: '8px'
                  }}
                  formatter={(value, name) => [`${value}%`, name]}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <p className="text-center text-2xl font-bold mt-2">
            {displayData.increaseRateNum >= 0 ? (
              <span className="text-green-400">+{displayData.increaseRateNum.toFixed(1)}%</span>
            ) : (
              <span className="text-red-400">{displayData.increaseRateNum.toFixed(1)}%</span>
            )}
          </p>
        </div>
        <div className="flex flex-col">
          <h3 className="text-center mb-2 text-gray-300">负荷分布</h3>
          <div className="flex-1">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={loadData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  paddingAngle={5}
                  dataKey="value"
                >
                  {loadData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index + 2 % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: '#333',
                    borderColor: '#555',
                    borderRadius: '8px'
                  }}
                  formatter={(value, name) => [`${value} MW`, name]}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <p className="text-center text-xl mt-2">
            <span className="text-purple-400">{displayData.prediction.toFixed(2)} MW</span>
            <span className="text-gray-400 mx-2">/</span>
            <span className="text-blue-400">{displayData.capacity.toFixed(2)} MW</span>
          </p>
        </div>
      </div>
    </div>
  );
}
